package com.leyou.test1.multithread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : LiuDong
 * @date : Created in 2018/10/26 17:45
 */
public class ThreadTest {

    /**
     * 模拟100米赛跑,8名选手已经准备就绪,只等裁判一声令下.当所有人都到达终点时,比赛结束.
     * @param args 参数
     * @throws InterruptedException 异常
     */
    public static void main(String[] args) throws InterruptedException {
        // 开始的倒数锁
        final CountDownLatch begin = new CountDownLatch(1);
        // 结束的倒数锁
        final CountDownLatch end = new CountDownLatch(8);
        // 十名选手
        final ExecutorService exec = Executors.newFixedThreadPool(8);

        for (int i = 0; i < 8; i++) {
            final int NO = i + 1;
            //匿名对象
            Runnable run = new Runnable() {
                public void run() {
                    try {
                        // 如果当前计数为零,则此方法立即返回
                        // 等待
                        begin.await();
                        //方法体
                        System.out.println("No." + NO + "arrived");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        // 每个选到达终点是,end就减一
                        end.countDown();
                    }
                }
            };
            exec.submit(run);
        }
        System.out.println("Game Start");
        // begin减一,开始游戏
        begin.countDown();
        // 等待end变为0,即所有选手都到达终点
        end.await();
        System.out.println("Game Over");
        exec.shutdown();
    }
}
